package com.itqf.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * projectName: shop_manage
 *
 * @author: MaTianWei
 * time: 2021/7/13 14:58
 * description:定义类型转换器
 */
//指定要转换成java的数据类型
@MappedTypes(Integer[].class)
//数据库的数据类型
@MappedJdbcTypes(JdbcType.VARCHAR)
public class StringToIntegerArrayTypeHandler extends BaseTypeHandler<Integer []> {
    //JockJSON保重的工具类，可以在字符串和数组之间互相转换
    public static final ObjectMapper objectMapper = new ObjectMapper();
    //插入数据

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Integer[] integers, JdbcType jdbcType) throws SQLException {
        //objectMapper writer 将其他类型转换成字符串类型
        //objectMapper reader 将字符串类型转换成其他类型
        String str =null;
        try {
           str = objectMapper.writeValueAsString(integers);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        preparedStatement.setObject(i,str);
    }

    @Override
    public Integer[] getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        Integer[] ids = new Integer[0];
        try {
             ids = objectMapper.readValue(resultSet.getString(columnName),Integer[].class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ids;
    }

    @Override
    public Integer[] getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        Integer[] ids = new Integer[0];
        try {
            ids = objectMapper.readValue(resultSet.getString(columnIndex),Integer[].class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ids;
    }

    @Override
    public Integer[] getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        Integer[] ids = new Integer[0];
        try {
            ids = objectMapper.readValue(callableStatement.getString(i), Integer[].class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ids;
    }
}

